
package com.yami.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yami.shop.bean.model.AttachFile;
import com.yami.shop.common.bean.Qiniu;
import com.yami.shop.common.util.ImgUploadUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.AttachFileMapper;
import com.yami.shop.service.AttachFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 */
@Service
public class AttachFileServiceImpl extends ServiceImpl<AttachFileMapper, AttachFile> implements AttachFileService {
	private final Logger logger = LoggerFactory.getLogger(AttachFileServiceImpl.class);
    @Autowired
    private AttachFileMapper attachFileMapper;
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private BucketManager bucketManager;
	@Autowired
	private Qiniu qiniu;
    @Autowired
    private Auth auth;
	@Autowired
	private ImgUploadUtil imgUploadUtil;
    public final static String NORM_MONTH_PATTERN = "yyyy/MM/";


	private OSSClient client;
	private String aliyunDomain="https://ysmshop.oss-cn-guangzhou.aliyuncs.com";
	private String aliyunEndPoint="oss-cn-guangzhou.aliyuncs.com";
	private String aliyunAccessKeyId="LTAI5tHrk6Wur6VxNjV54Ctx";
	private String aliyunAccessKeySecret="6JznYv7eDVDu2e8IBFG84aqPRvbYJv";
	private String aliyunBucketName="xxx";

	private COSClient txCosClient;
	private Long qcloudAppId= 1318150516L;
	private String qcloudSecretId= "AKIDphdhj6UsAQhvBUo8JI1iHdx85qCOVajr";
	private String qcloudSecretKey = "3sY1QgokS1WxFZtDNL6mZCpU2OamsodJ";
	private String qcloudRegion = "ap-guangzhou";
	private String qcloudBucketName = "zkyyunshop-1318150516";

	public AttachFileServiceImpl(){
		//client = new OSSClient(aliyunEndPoint,aliyunAccessKeyId,aliyunAccessKeySecret);

		COSCredentials credentials = new BasicCOSCredentials(qcloudSecretId,qcloudSecretKey);
		//初始化客户端配置
		ClientConfig clientConfig = new ClientConfig(new Region(qcloudRegion));
		txCosClient = new COSClient(credentials, clientConfig);
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String uploadFile(MultipartFile file) throws IOException {
		String extName = FileUtil.extName(file.getOriginalFilename());
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(file.getBytes().length);
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
			// 本地文件上传
			attachFileMapper.insert(attachFile);
			return imgUploadUtil.upload(file, fileName);
		} else {
			// 七牛云文件上传
			String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
			Response response = uploadManager.put(file.getBytes(), fileName, upToken);
			Json.parseObject(response.bodyString(),  DefaultPutRet.class);
			return fileName;
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public String uploadFile(MultipartFile file, String originalName) throws IOException {
		String extName = FileUtil.extName(originalName);
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
		AttachFile attachFile = new AttachFile();
		attachFile.setFilePath(fileName);
		attachFile.setFileSize(Integer.parseInt(file.getSize()+""));
		attachFile.setFileType(extName);
		attachFile.setUploadTime(new Date());
		attachFileMapper.insert(attachFile);
		if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
			// 本地文件上传
			//attachFileMapper.insert(attachFile);
			return imgUploadUtil.upload(file, fileName);
		}

		//阿里云
		//client.putObject(aliyunBucketName, fileName,file.getInputStream() );

		try {
			//腾讯云
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(file.getInputStream().available());
			objectMetadata.setHeader("expires", DateUtil.offsetMinute(DateUtil.date(),3).getTime());
			PutObjectRequest putObjectRequest = new PutObjectRequest(qcloudBucketName, fileName, file.getInputStream(),objectMetadata);

			PutObjectResult putObjectResult = txCosClient.putObject(putObjectRequest);

			logger.info("文件上传data：{}" , JSONUtil.toJsonStr(putObjectResult));

		}catch (Exception e){
			logger.info("文件上传失败：{}" ,fileName );
		}
		return fileName;
	}

	@Override
	public void deleteFile(String fileName){
		attachFileMapper.delete(new LambdaQueryWrapper<AttachFile>().eq(AttachFile::getFilePath,fileName));
		try {
			if (Objects.equals(imgUploadUtil.getUploadType(), 1)) {
				imgUploadUtil.delete(fileName);
			} else if (Objects.equals(imgUploadUtil.getUploadType(), 2)) {
				bucketManager.delete(qiniu.getBucket(), fileName);
			}
		} catch (QiniuException e) {
			throw new RuntimeException(e);
		}
	}
}
